package com.request.service.impl.shop.sy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.SignTypeEnum;
import com.request.common.enums.SyOrderStatusEnum;
import com.request.common.utils.HttpUtils;
import com.request.common.utils.SignUtils;
import com.request.entity.PhoneOrderAvailable;
import com.request.entity.PhoneOrderWaitPush;
import com.request.entity.out.PushOrderForSy;
import com.request.service.PushOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Create DateTime: 2020/6/10 16:12
 *
 * 

 */
@Slf4j
@Service
public class SyPushOrderProcessor implements PushOrderProcessor {
    private static final Map<String, String> HEADER_MAP = new HashMap<>(2);

    static {
        HEADER_MAP.put("Accept", "application/json;charset=utf-8");
    }

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public void sendRequest(PhoneOrderWaitPush phoneOrderWaitPush) {
        handlerOrderExecutor.execute(() -> executeSend(phoneOrderWaitPush));
    }

    private void executeSend(PhoneOrderWaitPush phoneOrderWaitPush) {
        if (phoneOrderWaitPush == null) {
            return;
        }
        PhoneOrderAvailable phoneOrderAvailable = phoneOrderWaitPush.getPhoneOrderAvailable();
        PushOrderForSy pushOrderForSy = new PushOrderForSy();
        String result = null;
        try {
            //组装参数
            pushOrderForSy.setCoopid(phoneOrderWaitPush.getAppId());
            pushOrderForSy.setTranid(phoneOrderAvailable.getPlatformOrderNo());
            pushOrderForSy.setPhone(phoneOrderAvailable.getPhoneNum());
            pushOrderForSy.setPrice(phoneOrderAvailable.getOrderPrice().toString());

            //生成签名
            TreeMap<String, String> signMap = new TreeMap<>();
            signMap.put("coopid", pushOrderForSy.getCoopid());
            signMap.put("tranid", pushOrderForSy.getTranid());
            signMap.put("phone", pushOrderForSy.getPhone());
            signMap.put("price", pushOrderForSy.getPrice());

            String sign = SignUtils.syGenerateSignature(signMap, SignTypeEnum.MD5, phoneOrderWaitPush.getAppKey());
            pushOrderForSy.setSign(sign.toLowerCase());

            String param = JSON.toJSONString(pushOrderForSy);

            log.info("【Sy】【推单】组装参数:{}", param);

            try {
                result = sendRequestForPushOrder(phoneOrderWaitPush.getPushSite(), param);
            } catch (Exception e) {
                savePushOrderForException(phoneOrderWaitPush);
                savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
                log.info("【Sy】【推单】发送请求出现异常：", e);
                return;
            }

            log.info("【Sy】【推单】订单为：{}, 结果:{}", phoneOrderAvailable.getPlatformOrderNo(), result);
            JSONObject json = JSONObject.parseObject(result);
            String code = json.getString("failedCode");

            if (SyOrderStatusEnum.PUSH_ORDER_FAIL.getCode().equals(code)) {
                log.info("【Sy】【推单】响应状态失败,状态为：{}", code);
                savePushOrderForFailed(phoneOrderWaitPush);
                return;
            }

            if (!SyOrderStatusEnum.PUSH_ORDER_SUCCESS.getCode().equals(code)) {
                String msg = json.getString("msg");
                throw new RuntimeException("推送订单商户相应失败，相应的状态码为 : " + code + ",对应的信息为 : " + msg);
            }
            savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
        } catch (Exception e) {
            savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
            log.error("【Sy】【推送订单】推送订单失败，待推送订单信息为：{}, 请求参数为：{}, 商户响应结果为：{}, 详细错误信息为：",
                    phoneOrderWaitPush, pushOrderForSy, result, e);
        }
    }

    //保留orderPrice小数点两位（例如100格式化为100.00）
    private BigDecimal formatBigDecimal(BigDecimal orderPrice) {
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String format = decimalFormat.format(orderPrice);
        BigDecimal formatOrderPrice = new BigDecimal(format);
        return formatOrderPrice;
    }

    ;

    /**
     * 放入失败队列
     *
     * @param phoneOrderWaitPush
     */
    private void savePushOrderForFailed(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_RECORD, JSON.toJSONString(phoneOrderWaitPush));
    }

    /**
     * 发送Http请求
     *
     * @param url            请求路径
     * @param pushOrderForHf 参数
     * @return 响应结果
     */
    private String sendRequestForPushOrder(String url, String pushOrderForHf) {
        return HttpUtils.jsonPost(url, pushOrderForHf);
    }

    /**
     * 放入成功队列
     */
    private void savePushOrderForSuccess(String platformOrderNo) {
        redisTemplate.opsForValue().set(RedisConstant.PUSH_ORDER_WAIT_PUSH_SUCCESS + platformOrderNo, platformOrderNo, 30, TimeUnit.MINUTES);
    }

    /**
     * 放入发送出现异常的队列
     */
    private void savePushOrderForException(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_EXCEPTION, JSON.toJSONString(phoneOrderWaitPush));
    }

}
